// 检查是否登录，未登录则跳转登录页面
export const checkLogin = () => {
  if (!uni.getStorageSync('token')) {
    // 获取当前页面路径
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const route = currentPage.route;
    const options = currentPage.options;
    
    // 判断是否是 tabbar 页面
    const tabbarPages = ['pages/home/index', 'pages/require/index', 'pages/cart/index','pages/news/index', 'pages/mine/index'];
    const isTabbarPage = tabbarPages.includes(route);
    
    // 将路径和参数存储到本地
    uni.setStorageSync('redirectUrl', {
      path: `/${route}`,
      query: options,
      isTabbarPage: isTabbarPage
    });
    // 跳转到登录页面
    uni.navigateTo({
      url: '/pages/login/index'
    });
    return false;
  }
  return true;
};

// 登录成功后跳转回原页面
export const redirectToOriginalPage = (code) => {
  const redirectUrl = uni.getStorageSync('redirectUrl');
 
  if (redirectUrl) {
    const { path, query, isTabbarPage } = redirectUrl;
    const queryString = Object.keys(query).map(key => `${key}=${query[key]}`).join('&');
    const url = queryString ? `${path}?${queryString}` : path;
    if (isTabbarPage) {
      wx.showToast({
        title: code==1?'跳转中...':"登录成功！数据加载中",
        icon: "none",
        duration: 2000,
      });
      setTimeout(() => {
        uni.switchTab({
          url: path
        });
      }, 1500);
      
    } else {
        if (path.includes('homeFurnish/index')||path.includes('homeFurnishSearch/index')) {
          
          uni.navigateBack({
              delta: 1,
              success: () => {
                wx.showToast({
                  title: code==1?'跳转中...':"登录成功！数据加载中",
                  icon: "none",
                  duration: 2000,
                });  
                setTimeout(() => {
                  uni.redirectTo({
                  url: url
                });
                }, 500);

              }
            });
          }else if (path.includes('common/index')){
            wx.showToast({
              title: code==1?'跳转中...':"登录成功！数据加载中",
              icon: "none",
              duration: 2000,
            });
            setTimeout(() => {
              uni.reLaunch({
                url: url
              });
            }, 1500);
            
          }else{
            wx.showToast({
              title: code==1?'跳转中...':"登录成功！数据加载中",
              icon: "none",
              duration: 2000,
            });
            
            setTimeout(() => {
              uni.redirectTo({
                url: url
              });
            }, 1500);
          }
      
    }
    uni.removeStorageSync('redirectUrl');
  } else {
    
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/home/index'
      });
    }, 1500);
  }
}; 